<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'
import { getBuildingController } from '@/api-client'
import type { Building, BuildingAddRequest, BuildingQueryRequest } from '@/api-client'

// 响应式数据
const loading = ref(false)
const tableData = ref<Building[]>([])
const total = ref(0)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const multipleSelection = ref<Building[]>([])

// 分页参数
const pagination = reactive({
  current: 1,
  pageSize: 10,
})

// 查询表单
const queryForm = reactive<BuildingQueryRequest>({
  current: 1,
  pageSize: 10,
  numbers: '',
  units: '',
  remarks: '',
})

// 新增/编辑表单
const buildingForm = reactive<BuildingAddRequest>({
  numbers: '',
  units: '',
  remarks: '',
})

// 当前编辑的楼宇ID
const currentEditId = ref<number>()

// 表单验证规则
const rules = reactive<FormRules<BuildingAddRequest>>({
  numbers: [
    { required: true, message: '请输入楼栋号码', trigger: 'blur' },
    { max: 50, message: '楼栋号码不能超过50个字符', trigger: 'blur' },
  ],
  units: [
    { required: true, message: '请输入单元号码', trigger: 'blur' },
    { max: 50, message: '单元号码不能超过50个字符', trigger: 'blur' },
  ],
  remarks: [{ max: 200, message: '备注信息不能超过200个字符', trigger: 'blur' }],
})

// 获取楼宇列表
const fetchBuildingList = async () => {
  loading.value = true
  try {
    const { queryBuildingByPage } = getBuildingController()
    const response = await queryBuildingByPage({
      ...queryForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    })

    console.log('Building API Response:', response)

    if (response.data?.records) {
      tableData.value = response.data.records
      total.value = response.data.total || 0
    }
  } catch (error) {
    ElMessage.error('获取楼宇列表失败')
    console.error('Error fetching building list:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchBuildingList()
}

// 重置搜索
const handleReset = () => {
  queryForm.numbers = ''
  queryForm.units = ''
  queryForm.remarks = ''
  pagination.current = 1
  fetchBuildingList()
}

// 分页变化
const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchBuildingList()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchBuildingList()
}

// 打开新增对话框
const handleAdd = () => {
  isEdit.value = false
  buildingForm.numbers = ''
  buildingForm.units = ''
  buildingForm.remarks = ''
  currentEditId.value = undefined
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row: Building) => {
  isEdit.value = true
  buildingForm.numbers = row.numbers || ''
  buildingForm.units = row.units || ''
  buildingForm.remarks = row.remarks || ''
  currentEditId.value = row.id
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const { addBuilding, updateBuilding } = getBuildingController()

        if (isEdit.value && currentEditId.value) {
          await updateBuilding(currentEditId.value, buildingForm)
          ElMessage.success('编辑楼宇成功')
        } else {
          await addBuilding(buildingForm)
          ElMessage.success('新增楼宇成功')
        }

        dialogVisible.value = false
        fetchBuildingList()
      } catch (error) {
        ElMessage.error(isEdit.value ? '编辑楼宇失败' : '新增楼宇失败')
        console.error('Error submitting form:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 取消对话框
const handleCancel = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 删除单个楼宇
const handleDelete = async (row: Building) => {
  if (!row.id) return

  try {
    await ElMessageBox.confirm(`确定要删除楼宇"${row.numbers} ${row.units}"吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    loading.value = true
    const { deleteBuilding } = getBuildingController()
    await deleteBuilding({ id: row.id })
    ElMessage.success('删除成功')
    fetchBuildingList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('Error deleting building:', error)
    }
  } finally {
    loading.value = false
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的楼宇')
    return
  }

  const buildingNames = multipleSelection.value
    .map((item) => `${item.numbers} ${item.units}`)
    .join('、')

  try {
    await ElMessageBox.confirm(`确定要删除以下楼宇吗？\n${buildingNames}`, '确认批量删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    loading.value = true
    const ids = multipleSelection.value
      .map((item) => item.id)
      .filter((id): id is number => id !== undefined)

    const { deleteBuildingBatch } = getBuildingController()
    await deleteBuildingBatch(ids)
    ElMessage.success('批量删除成功')
    fetchBuildingList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
      console.error('Error batch deleting buildings:', error)
    }
  } finally {
    loading.value = false
  }
}

// 选择变化
const handleSelectionChange = (selection: Building[]) => {
  multipleSelection.value = selection
}

// 页面加载时获取数据
onMounted(() => {
  fetchBuildingList()
})
</script>

<template>
  <div class="building-view">
    <div class="page-header">
      <h2>楼宇管理</h2>
      <p>管理小区内的楼宇信息</p>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="queryForm" inline class="search-form">
        <el-form-item label="楼栋号码">
          <el-input
            v-model="queryForm.numbers"
            placeholder="请输入楼栋号码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="单元号码">
          <el-input
            v-model="queryForm.units"
            placeholder="请输入单元号码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="queryForm.remarks"
            placeholder="请输入备注信息"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"> 搜索 </el-button>
          <el-button :icon="Refresh" @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作区域 -->
    <div class="action-section">
      <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增楼宇 </el-button>
      <el-button
        type="danger"
        :icon="Delete"
        :disabled="multipleSelection.length === 0"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="numbers" label="楼栋号码" min-width="120" />
        <el-table-column prop="units" label="单元号码" min-width="120" />
        <el-table-column prop="remarks" label="备注信息" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑楼宇' : '新增楼宇'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="buildingForm" :rules="rules" label-width="100px">
        <el-form-item label="楼栋号码" prop="numbers">
          <el-input
            v-model="buildingForm.numbers"
            placeholder="请输入楼栋号码，如：1栋、2栋"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="单元号码" prop="units">
          <el-input
            v-model="buildingForm.units"
            placeholder="请输入单元号码，如：1单元、2单元"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input
            v-model="buildingForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmit(formRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="css" scoped>
.building-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.action-section {
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background-color: #fafafa;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}
</style>
